
package rendi456.swing.gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.AbstractAction;
import javax.swing.JFrame;

public abstract class GuiManager
{
	private JFrame mainWindow = null;
	private MainWindowListener mainWindowListener = null;

	private ExitAction exitAct = null;

	private int exitCode = 0;

	public GuiManager()
	{
		this.mainWindowListener = new MainWindowListener();
		this.initActions();
		this.initMainWindow();
	}

	private void initMainWindow()
	{
		this.mainWindow = new MainWindow();
		this.mainWindow.addWindowListener(this.mainWindowListener);
		this.mainWindow.setLayout(new BorderLayout());
		this.mainWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
	}

	private void initActions()
	{
		this.exitAct = new ExitAction();
	}

	public void launch()
	{
		this.mainWindow.setVisible(true);
	}

	protected JFrame getMainWindow()
	{
		return this.mainWindow;
	}

	protected int getExitCode()
	{
		return this.exitCode;
	}

	protected boolean setExitCode(int exitCode)
	{
		this.exitCode = exitCode;
		return true;
	}

	protected void exit()
	{
		System.exit(this.exitCode);
	}

	protected AbstractAction getExitAction()
	{
		return this.exitAct;
	}

	protected void windowActivated(WindowEvent e)
	{
	}

	protected void windowDeactivated(WindowEvent e)
	{
	}

	protected void onStart()
	{
	}

	protected void onClose()
	{
	}

	private class MainWindow extends JFrame
	{
		public MainWindow()
		{

		}

		@Override
		public void setVisible(boolean visible)
		{
			if (!visible)
			{
				GuiManager.this.onClose();
			}

			super.setVisible(visible);

			if (visible)
			{
				GuiManager.this.onStart();
			}
		}
	}

	private class ExitAction extends AbstractAction
	{
		public ExitAction()
		{
			super("Exit");
		}

		@Override
		public void actionPerformed(ActionEvent e)
		{
			GuiManager.this.exit();
		}
	}

	private class MainWindowListener implements WindowListener
	{
		@Override
		public void windowActivated(WindowEvent e)
		{
			GuiManager.this.windowActivated(e);
		}

		@Override
		public void windowClosed(WindowEvent e)
		{
		}

		@Override
		public void windowClosing(WindowEvent e)
		{
			GuiManager.this.exit();
		}

		@Override
		public void windowDeactivated(WindowEvent e)
		{
			GuiManager.this.windowDeactivated(e);
		}

		@Override
		public void windowDeiconified(WindowEvent e)
		{
		}

		@Override
		public void windowIconified(WindowEvent e)
		{
		}

		@Override
		public void windowOpened(WindowEvent e)
		{
		}
	}
}
